import { defineStore } from 'pinia'
import { login, logout, getInfo } from '@/api/user'
import { setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: {},
    roles: []
  }),

  actions: {
    // 登录
    async login(userInfo) {
      const { username, password } = userInfo
      const { data } = await login({ username: username.trim(), password })
      this.token = data.token
      setToken(data.token)
      return data
    },

    // 获取用户信息
    async getUserInfo() {
      const { data } = await getInfo()
      if (!data) {
        throw new Error('Verification failed, please Login again.')
      }
      const { roles, user } = data
      if (!roles || roles.length <= 0) {
        throw new Error('getInfo: roles must be a non-null array!')
      }
      this.roles = roles
      this.userInfo = user
      return data
    },

    // 退出登录
    async logout() {
      try {
        await logout()
      } catch (error) {
        console.log(error)
      } finally {
        this.token = ''
        this.roles = []
        this.userInfo = {}
        removeToken()
        localStorage.removeItem('token')
      }
    },

    // 重置token
    resetToken() {
      this.token = ''
      this.roles = []
      this.userInfo = {}
      removeToken()
      localStorage.removeItem('token')
    }
  }
})
